package ch.headshot.photomap.client.gpx.impl;

import java.util.ArrayList;
import java.util.List;

import ch.headshot.photomap.client.gpx.Gpx;
import ch.headshot.photomap.client.gpx.Route;
import ch.headshot.photomap.client.gpx.Track;
import ch.headshot.photomap.client.gpx.WayPoint;

import com.google.gwt.xml.client.Element;
import com.google.gwt.xml.client.NodeList;

public class GpxImpl implements Gpx {

	private static final String RTE_ELEM = "rte";
	private static final String METADATA_ELEM = "metadata";
	private static final String WPT_ELEM = "wpt";
	private static final String TRK_ELEM = "trk";
	private static final String EXTENSIONS_ELEM = "extensions";

	private final Element gpx;
	private ArrayList<Track> tracks;

	public GpxImpl(Element gpx) {
		this.gpx = gpx;
	}

	@Override
	public String toString() {
		StringBuffer b = new StringBuffer("<gpx>");
		for (Track track : getTracks()) {
			b.append(track);
		}
		b.append("</gpx>");
		return b.toString();
	}

	public List<Route> getRoutes() {
		List<Route> result = new ArrayList<Route>();
		NodeList rtes = gpx.getElementsByTagName(RTE_ELEM);
		for (int i = 0; i < rtes.getLength(); i++) {
			result.add(new RouteImpl((Element) rtes.item(i)));
		}
		return result;
	}

	public List<Track> getTracks() {
		if (tracks == null) {
			tracks = new ArrayList<Track>();
			NodeList rtes = gpx.getElementsByTagName(TRK_ELEM);
			for (int i = 0; i < rtes.getLength(); i++) {
				tracks.add(new TrackImpl((Element) rtes.item(i)));
			}
		}
		return tracks;

	}

	public List<WayPoint> getWayPoints() {
		List<WayPoint> result = new ArrayList<WayPoint>();
		NodeList rtes = gpx.getElementsByTagName(WPT_ELEM);
		for (int i = 0; i < rtes.getLength(); i++) {
			result.add(new WayPointImpl((Element) rtes.item(i)));
		}
		return result;
	}

}
